package com.bugstack.infrastructure.event;

import com.alibaba.fastjson.JSON;
import com.bugstack.types.event.BaseEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Author: czb
 * @Description: 事件发布器
 * @DateTime: 2025/3/23 14:00
 **/
@Slf4j
@Component
public class EventPublisher {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    public void publish(String topic, BaseEvent.EventMessage<?> event) {
        try {
            String jsonString = JSON.toJSONString(event);
            rabbitTemplate.convertAndSend(topic, jsonString);
            log.info("发送mq消息 event:{} -> topic:{}", event, topic);
        }catch (Exception e) {
            log.error("发送mq消息失败 event:{} -> topic:{}", event, topic, e);
            throw e;
        }
    }

    public void publish(String topic, String eventMessageJSON){
        try {
            rabbitTemplate.convertAndSend(topic, eventMessageJSON);
            log.info("发送MQ消息 topic:{} message:{}", topic, eventMessageJSON);
        } catch (Exception e) {
            log.error("发送MQ消息失败 topic:{} message:{}", topic, eventMessageJSON, e);
            throw e;
        }
    }

}
